{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c6430ac3",
   "metadata": {},
   "source": [
    "# Basic Browser tool usage with Browser-Use SDK\n",
    "\n",
    "## Overview\n",
    "\n",
    "In this tutorial we will learn how to use the open source Browser-Use SDK with Amazon Bedrock Agentcore Browser tool. We will provide examples of using the browser tool headless and view the browser live.\n",
    "\n",
    "\n",
    "### Tutorial Details\n",
    "\n",
    "\n",
    "| Information         | Details                                                                                   |\n",
    "|:--------------------|:-------------------------------------------------------------------------------------------        \n",
    "| Tutorial type       | Conversational                                                                            |\n",
    "| Agent type          | Single                                                                                    |\n",
    "| Agentic Framework   | Broeser-Use                                                                               |\n",
    "| LLM model           | Anthropic Claude 3.5 Sonnet                                                               |\n",
    "| Tutorial components | Using Browser-Use SDK to interact with Bedrock Agentcore browser tool in a headless way   |\n",
    "| Tutorial vertical   | Cross-vertical                                                                            |\n",
    "| Example complexity  | Easy                                                                                      |\n",
    "| SDK used            | Amazon BedrockAgentCore Python SDK, Browser-Use                                           |\n",
    "\n",
    "### Tutorial Architecture\n",
    "\n",
    "In this tutorial we will describe how to use Browser-Use SDK with Agentcore browser tool.  \n",
    "\n",
    "In our example we will send natural language instructions to Browser-Use agent to perform tasks on the Bedrock Agentcore browser in a headless way.\n",
    "\n",
    "<div style=\"text-align:left\">\n",
    "    <img src=\"images/architecture_runtime.png\" width=\"50%\"/>\n",
    "</div>\n",
    "\n",
    "### Tutorial Key Features\n",
    "\n",
    "* Using browser tool in a headless way\n",
    "* Using Browser-Use with browser tool"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ea131f7",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "To execute this tutorial you will need:\n",
    "* Python 3.11+\n",
    "* AWS credentials\n",
    "* Amazon Bedrock AgentCore SDK\n",
    "* Browser-Use SDK "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1212a355",
   "metadata": {},
   "source": [
    "## How it works\n",
    "\n",
    "A browser tool sandbox is a secure execution environment that enables AI agents to safely interact with web browsers. When a user makes a request, the Large Language Model (LLM) selects appropriate tools and translates commands. These commands are executed within a controlled sandbox environment containing a headless browser and hosted library server (using tools like Playwright). The sandbox provides isolation and security by containing web interactions within a restricted space, preventing unauthorized system access. The agent receives feedback through screenshots and can perform automated tasks while maintaining system security. \n",
    "\n",
    "![architecture local](../images//browser-tool.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "564f8445",
   "metadata": {},
   "source": [
    "## 1. Setting Up the Environment\n",
    "\n",
    "First, let's install and import the necessary libraries to initiaize the browser tool sandbox client. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "714f2462",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -r requirements.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a89f7eab",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bedrock_agentcore.tools.browser_client import BrowserClient\n",
    "from browser_use import Agent\n",
    "from browser_use.browser.session import BrowserSession\n",
    "from browser_use.browser import BrowserProfile\n",
    "from langchain_aws import ChatBedrockConverse\n",
    "from rich.console import Console\n",
    "from contextlib import suppress\n",
    "import asyncio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dad07098",
   "metadata": {},
   "outputs": [],
   "source": [
    "console = Console()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "093f3090",
   "metadata": {},
   "source": [
    "## 2. Setup the browser client\n",
    "We will setup the browser client and wait for it to be ready. Then, we will generate web-socket url and headers \n",
    " \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c532d851",
   "metadata": {},
   "outputs": [],
   "source": [
    "from boto3.session import Session\n",
    "boto_session = Session()\n",
    "region = boto_session.region_name\n",
    "\n",
    "client = BrowserClient(region)\n",
    "client.start()\n",
    "\n",
    "# Extract ws_url and headers\n",
    "ws_url, headers = client.generate_ws_headers()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a10a5875",
   "metadata": {},
   "source": [
    "## 4. Helper function to run browser task\n",
    "Run a browser automation task using browser-use Agent \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9084345a",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def run_browser_task(browser_session: BrowserSession, bedrock_chat: ChatBedrockConverse, task: str) -> None:\n",
    "    \"\"\"\n",
    "    Run a browser automation task using browser_use\n",
    "    \n",
    "    Args:\n",
    "        browser_session: Existing browser session to reuse\n",
    "        bedrock_chat: Bedrock chat model instance\n",
    "        task: Natural language task for the agent\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # Show task execution\n",
    "        console.print(f\"\\n[bold blue]🤖 Executing task:[/bold blue] {task}\")\n",
    "        \n",
    "        # Create and run the agent\n",
    "        agent = Agent(\n",
    "            task=task,\n",
    "            llm=bedrock_chat,\n",
    "            browser_session=browser_session\n",
    "        )\n",
    "        \n",
    "        # Run with progress indicator\n",
    "        with console.status(\"[bold green]Running browser automation...[/bold green]\", spinner=\"dots\"):\n",
    "            await agent.run()\n",
    "        \n",
    "        console.print(\"[bold green]✅ Task completed successfully![/bold green]\")\n",
    "        \n",
    "    except Exception as e:\n",
    "        console.print(f\"[bold red]❌ Error during task execution:[/bold red] {str(e)}\")\n",
    "        import traceback\n",
    "        if console.is_terminal:\n",
    "            traceback.print_exc()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b9f974e",
   "metadata": {},
   "source": [
    "## 5. Invoke the browser task using Browser-use profile\n",
    "Create a persistent browser session using CDP WebSocket connection and initialize Bedrock Claude model for automated web tasks. Handle session lifecycle with proper cleanup and execute browser automation tasks via AI-driven commands."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b3706b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create persistent browser session and model\n",
    "browser_session = None\n",
    "bedrock_chat = None\n",
    "\n",
    "try:\n",
    "    # Create browser profile with headers\n",
    "    browser_profile = BrowserProfile(\n",
    "        headers=headers,\n",
    "        timeout=1500000,  # 150 seconds timeout\n",
    "    )\n",
    "    \n",
    "    # Create a browser session with CDP URL and keep_alive=True for persistence\n",
    "    browser_session = BrowserSession(\n",
    "        cdp_url=ws_url,\n",
    "        browser_profile=browser_profile,\n",
    "        keep_alive=True  # Keep browser alive between tasks\n",
    "    )\n",
    "    \n",
    "    # Initialize the browser session\n",
    "    console.print(\"[cyan]🔄 Initializing browser session...[/cyan]\")\n",
    "    await browser_session.start()\n",
    "    \n",
    "    # Create ChatBedrockConverse once\n",
    "    bedrock_chat = ChatBedrockConverse(\n",
    "        model_id=\"anthropic.claude-3-5-sonnet-20240620-v1:0\",\n",
    "        region_name=\"us-west-2\"\n",
    "    )\n",
    "    \n",
    "    console.print(\"[green]✅ Browser session initialized and ready for tasks[/green]\\n\")\n",
    "\n",
    "    task = \"Search for a coffee maker on amazon.com and extract details of the first one\" ## Modify the task to run other tasks\n",
    "\n",
    "    await run_browser_task(browser_session, bedrock_chat, task)\n",
    "\n",
    "finally:\n",
    "    # Close the browser session\n",
    "    if browser_session:\n",
    "        console.print(\"\\n[yellow]🔌 Closing browser session...[/yellow]\")\n",
    "        with suppress(Exception):\n",
    "            await browser_session.close()\n",
    "        console.print(\"[green]✅ Browser session closed[/green]\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6597132",
   "metadata": {},
   "source": [
    "## 6. Cleanup\n",
    "Stop the browser session if it hasn't been"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99a79405",
   "metadata": {},
   "outputs": [],
   "source": [
    "client.stop()\n",
    "print(\"Browser session stopped successfully!\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "amazon-bedrock-agentcore-samples",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
